<template>
  <el-dialog
    v-model="dialogVisible"
    title="指定用户"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="用户" prop="userId">
        <el-select
          ref="userSelectRef"
          v-model="form.userId"
          placeholder="请选择"
          filterable
          remote
          :remote-method="onKeywordInput"
          class="w-full"
          clearable
          @visible-change="onUserDropdownVisibleChange"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
          <template v-if="userLoading" #footer>
            <div class="text-center text-xs text-gray-500">
              <span>加载中...</span>
            </div>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="是否强覆盖" prop="override">
        <el-switch v-model="form.override" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import { message } from "@/utils/message";
import { applyAdminTemplateHead } from "@/api/adminTemplateHeadApi";
import { type ElSelect } from "element-plus";
import { useRemotePagedSelect } from "@/composables/useRemotePagedSelect";
import {
  userSelectFetcher,
  type UserItem
} from "@/composables/userSelectFetcher";

// 用户下拉：远程搜索 + 触底加载
const {
  list,
  loading: userLoading,
  onKeywordInput,
  onDropdownScroll
} = useRemotePagedSelect<UserItem>({
  pageSize: 20,
  autoLoad: true,
  debounceMs: 300,
  fetcher: userSelectFetcher
});

const userSelectRef = ref<InstanceType<typeof ElSelect> | null>(null);
let userDropdownWrapEl: HTMLElement | null = null;

function onUserDropdownVisibleChange(visible: boolean) {
  if (visible) {
    nextTick(() => {
      const popperEl = userSelectRef.value?.popperRef as
        | HTMLElement
        | undefined;
      // 在该选择器自己的 popper 里找 wrap
      userDropdownWrapEl =
        popperEl?.querySelector(".el-select-dropdown__wrap") ?? null;
      userDropdownWrapEl?.addEventListener("scroll", onDropdownScroll, {
        passive: true
      });
    });
  } else {
    userDropdownWrapEl?.removeEventListener("scroll", onDropdownScroll);
    userDropdownWrapEl = null;
  }
}
const emits = defineEmits(["refresh"]);
const dialogVisible = ref(false);
const loading = ref(false);
const form = ref({
  userId: "",
  override: false
});
const templateId = ref("");
// 基础校验规则
const rules = {
  userId: [{ required: true, message: "请选择用户", trigger: "change" }]
};
const serviceForm = ref(null);
// 重置表单
const resetForm = () => {
  templateId.value = "";
  form.value = {
    userId: "",
    override: false
  };
  serviceForm.value?.clearValidate();
  serviceForm.value?.resetFields();
};

const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        const { message: text } = await applyAdminTemplateHead(
          templateId.value,
          form.value
        );
        emits("refresh");
        message(text || "更新成功", { type: "success" });
        dialogVisible.value = false;
      } catch (error) {
        console.log(error);
      } finally {
        loading.value = false;
      }
    }
  });
};
const open = (row: { id: string; userId: string; override: boolean }) => {
  if (row?.id) {
    templateId.value = row.id;
    form.value = {
      userId: row?.userId || "",
      override: row?.override
    };
  }
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
